<?php
// $Id$

/**
 * Smslog 封装来自 sms_log 数据表的记录及领域逻辑
 */
class video extends QDB_ActiveRecord_Abstract
{

    /**
     * 返回对象的定义
     *
     * @static
     *
     * @return array
     */
    static function __define()
    {
        return array
        (
            // 指定该 ActiveRecord 要使用的行为插件
            'behaviors' => '',

            // 指定行为插件的配置
            'behaviors_settings' => array
            (
                # '插件名' => array('选项' => 设置),
            ),

            // 用什么数据表保存对象
            'table_name' => 'edu_video',

            // 指定数据表记录字段与对象属性之间的映射关系
            // 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
            'props' => array
            (
                // 主键应该是只读，确保领域对象的“不变量”
                'id' => array('readonly' => true),

                // 对象创建时间应该是只读
                'addtime' => array('readonly' => true),


                /**
                 *  可以在此添加其他属性的设置
                 */
                # 'other_prop' => array('readonly' => true),

                /**
                 * 添加对象间的关联
                 */
                # 'other' => array('has_one' => 'Class'),
//         	'agent'=>array('has_one'=>'acct','source_key'=>'agent_id','target_id'=>'id'),
//             'admin'=>array('has_one'=>'acct','source_key'=>'admin_id','target_id'=>'id')

            ),

            /**
             * 允许使用 mass-assignment 方式赋值的属性
             *
             * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
             */
            'attr_accessible' => '',

            /**
             * 拒绝使用 mass-assignment 方式赋值的属性
             */
            'attr_protected' => 'id',

            /**
             * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
             *
             * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
             */
            'create_reject' => '',

            /**
             * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
             */
            'update_reject' => '',

            /**
             * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
             *
             * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
             * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
             *
             * 如果填充值为一个数组，则假定为 callback 方法。
             */
            'create_autofill' => array
            (
                # 属性名 => 填充值
                # 'is_locked' => 0,
                'addtime' => self::AUTOFILL_TIMESTAMP ,
                'acct_id'=>1,
            ),

            /**
             * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
             *
             * 填充值的指定规则同 create_autofill
             */
            'update_autofill' => array
            (
            ),

            /**
             * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
             *
             * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
             *
             * 如果需要添加一个自定义验证，应该写成
             *
             * 'title' => array(
             *        array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
             * )
             *
             * 然后在该类中添加 checkTitle() 方法。函数原型如下：
             *
             * static function checkTitle($title)
             *
             * 该方法返回 true 表示通过验证。
             */
            'validations' => array
            (
                
            ),
        );
    }


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

    /**
     * 开启一个查询，查找符合条件的对象或对象集合
     *
     * @static
     *
     * @return QDB_Select
     */
    static function find()
    {
        $args = func_get_args();
        return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
    }

    /**
     * 返回当前 ActiveRecord 类的元数据对象
     *
     * @static
     *
     * @return QDB_ActiveRecord_Meta
     */
    static function meta()
    {
        return QDB_ActiveRecord_Meta::instance(__CLASS__);
    }


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
    function _after_create_post(){
        $videocate = educategory::find('id = '.$this->class_id)->getOne();
        $this->cat_id = $videocate->pid;
        $this->save();
    }

    function _after_update_post(){
        //删除缓存
        $host = Helper_Common::getRequestHost();
        			$filename = Q::ini('app_config/ROOT_DIR').'/config/redis.yaml';
			$config = Helper_YAML::load($filename);
			$redis = new Redis();
			$redis->pconnect($config['host'],$config['port']);
        if($redis->exists("edulive:$host:video:".$this->id)){
            $redis->del("edulive:$host:video:".$this->id);
        }
    }

    static function getvideoinfo($id){
        if(empty($id)){
            return false;
        }
        $host = Helper_Common::getRequestHost();
        			$filename = Q::ini('app_config/ROOT_DIR').'/config/redis.yaml';
			$config = Helper_YAML::load($filename);
			$redis = new Redis();
			$redis->pconnect($config['host'],$config['port']);
        $rv = $redis->get("edulive:$host:video:".$id);
        if(!empty($rv)){
            return json_decode($redis->get("edulive:$host:video:".$id),true);
        }else{

            $info = video::find(array("id"=>intval($id)))->getOne();
            if($info->id()){
                $info = video::find(array("id"=>intval($id)))->asArray()->getOne();
            }else{
                return [];
            }
            $redis->set("edulive:$host:video:".$id,json_encode($info));
            $redis->expire("edulive:$host:video:".$id,86400);
            $redis->close();
            return $info;
        }
    }

    //根据ids批量获取视频
    static function getvideobyids($acct_id,$ids,$version=null){
        $arr = explode(',', trim($ids,','));
        $res = array();
        $live_auth = acct::checkversion($acct_id,$version);
        for ($i=0; $i < count($arr); $i++) { 
            $video_info = video::getvideoinfo($arr[$i]);
            //判断上下架状态
            if(!empty($video_info['status']) && $video_info['status'] == 1){
                //判断直播屏蔽
                if($live_auth || $video_info['style']!=3){
                    //判断拼团
                    if($video_info['is_pintuan']>0){
                        //获取拼团价格
                        $video_info['pintuan_price'] = videopintuan::find("video_id = ".$arr[$i])->getMin('price');
                    }
                    //判断章节
                    if($video_info['style']!=0){
                        //获取章节数量
                        $video_info['chapter'] = videochapter::find("video_id = ".$arr[$i])->asArray()->getAll();
                        $video_info['chapter_sum']=count($video_info['chapter']);
                    }
                    //获取tag信息
                    $tag = videotag::find('id = '.$video_info['tag_id'])->getOne();
                    $video_info['tagname']=$tag->name;
                    $video_info['color']=$tag->color;
                    $video_info['position']=$tag->position;
                    $video_info['virtual_pintuannum']=intval($video_info['virtual_pintuannum']);
                    $video_info['virtual_sellnum']=intval($video_info['virtual_sellnum']);
                    array_push($res, $video_info);
                }
            }
            
        }
        return $res;
    }

    static function getliveselect($acct_id){
        $video = video::find(
            array("acct_id"=>$acct_id,
                "style"=>3,
                "status"=>1
                ))->setColumns("id,title")->asArray()->getAll();
        array_unshift($video, array("id"=>0,"title"=>"请选择"));
        $result = Helper_Array::toHashmap($video, 'id','title');
        return $result;
    }


    //首页直播列表
    static function getindexlivelist($acct_id,$limit = null){
        $sql = "SELECT
            edu_video.id AS id,
            edu_video_tag.id AS tag_id,
            edu_video_tag.NAME AS tagname,
            position,
            color,
            title,
            pic_url,
            video_time,
            is_order,
            money,
            page_view,
            style,
            edu_video.is_pay,
            is_password,
            opening_time,
            present_price,
            original_price,
            shop_price 
        FROM
            edu_video
            LEFT JOIN edu_video_tag ON ( edu_video.tag_id = edu_video_tag.id )
        WHERE
            edu_video.acct_id = $acct_id 
            AND index_show = 1 
            AND edu_video.status = 1 
            AND style = 3 
        GROUP BY
            edu_video.id 
        ORDER BY
            sort";

        if($limit){
            $sql = $sql." limit $limit";
        }

        $live_index = QDB::getConn()->execute($sql)->fetchAll();
        if(count($live_index)){
            foreach ($live_index as &$v){
                $v['order_sum'] =  QDB::getConn()->execute("select count(*) from edu_video_order where video_id = {$v['id']} and is_pay=1")->fetchAll();
            }
        }

        return $live_index;
    }

    //获取首页视频列表
    static function getindexvideolist($acct_id,$style,$limit = null){
        $sql = "SELECT
            COUNT( edu_video_chapter.id ) AS chapter_sum,
            edu_video.id AS id,
            edu_video_tag.id AS tag_id,
            edu_video_tag.NAME AS tagname,
            position,
            color,
            title,
            pic_url,
            video_time,
            is_order,
            money,
            page_view,
            style,
            edu_video.is_pay,
            is_password,
            opening_time,
            present_price,
            original_price,
            shop_price
        FROM
            edu_video
            LEFT JOIN edu_video_tag ON ( edu_video.tag_id = edu_video_tag.id )
            LEFT JOIN edu_video_chapter ON ( edu_video.id = edu_video_chapter.video_id )
        WHERE
            edu_video.acct_id = $acct_id 
            AND edu_video.index_show = 1 
            AND edu_video.status = 1 
            AND edu_video.style = $style 
        GROUP BY
            edu_video.id 
        ORDER BY
            sort asc";

        if($limit){
            $sql = $sql." limit $limit";
        }

        $live_index = QDB::getConn()->execute($sql)->fetchAll();
        if(count($live_index)){
            foreach ($live_index as &$v){
                $sum = QDB::getConn()->execute("select count(*) from edu_video_order where video_id = {$v['id']} and is_pay=1")->fetchAll();
                $v['order_sum'] = $sum[0]['count(*)'];
                $v['opening_time'] = date("H:i",$v['opening_time']);
                if($v['opening_time']<time()){
                    $v['live_status']=0;
                }elseif($v['opening_time']>=time()){
                    $v['live_status']=1;
                }
            }
        }
        
        return $live_index;
    }

    //获取拼团视频列表
    static function pintuanvideolist($acct_id){
        $sql = "SELECT
            MIN(edu_video_pintuan.price) as pintuan_price,
            edu_video.id AS id,
            edu_video_tag.id AS tag_id,
            edu_video_tag.NAME AS tagname,
            position,
            color,
            title,
            pic_url,
            video_time,
            is_order,
            virtual_sellnum,
            virtual_pintuannum,
            money,
            page_view,
            style,
            edu_video.is_pay,
            is_password,
            opening_time,
            present_price,
            original_price,
            shop_price 
        FROM
            edu_video
            LEFT JOIN edu_video_tag ON ( edu_video.tag_id = edu_video_tag.id )
            LEFT JOIN edu_video_pintuan ON ( edu_video.id = edu_video_pintuan.video_id )
        WHERE
            edu_video.acct_id = $acct_id 
            AND is_pintuan = 1
            AND edu_video.status = 1 
        GROUP BY
            edu_video.id 
        ORDER BY
            sort asc";
        $list = QDB::getConn()->execute($sql)->fetchAll();
        for ($i=0; $i < count($list); $i++) { 
            $list[$i]['virtual_sellnum']=intval($list[$i]['virtual_sellnum']);
            $list[$i]['virtual_pintuannum']=intval($list[$i]['virtual_pintuannum']);
        }
        
        return $list;
    }



    //获取视频或者直播详情
    static function getvideodetail($id,$user_id,$password=null,$for_video_id=0){
        $video = video::getvideoinfo($id);
        //检查观看权限
        $video['AUTH'] = video::checkVideoAuth($id,$user_id,$password,$for_video_id);



        //检查收藏状态
        $video['collect'] = collect::checkcollect($id,$user_id);
        //检查是否支持预定
        if($video['is_order']==1 && $video['opening_time']>time()){
            $video['can_order'] = 1;
        }else{
            $video['can_order'] = 0;
        }
        //获取拼团价格
        if($video['is_pintuan']==1){
            $video['pintuan_price'] = videopintuan::getvideopintuanprice($id);
        }
        //章节信息
        if($video['style'] != 3){
            // $chapter = videochapter::find("video_id = $id")->order("weight asc")->asArray()->getAll();
            $chapter = videoquestion::getVideoQuestionList($id);
            $video['chapter'] = $chapter;
        }else{
            //关联权限检查
            if($video['AUTH']==false){
                //获取章节关联信息
                $live_chapter = videochapter::find(array("live_id"=>$id,"type"=>1))->getAll();
                foreach ($live_chapter as $value) {
                    if($value->video_id){
                        $auth = video::checkVideoAuth($value->video_id,$user_id,$password);
                        if($auth){
                            $video['AUTH']=true;
                            break;
                        }
                    }
                }
            }
            //价格继承
            if($for_video_id>0 && $video['AUTH']==false){
                $for_video_info = video::getvideoinfo($for_video_id);
                $video['present_price'] = $for_video_info['present_price'];
                $video['original_price'] = $for_video_info['original_price'];
            }
            //直播状态

            if($video['opening_time']<time()){
                if($video['end_time']<time()){
                    $video['live_status']=2;
                }else{
                    $video['live_status']=0;
                }
                
            }elseif($video['opening_time']>=time()){
                $video['live_status']=1;
                
            }
        }
        
        $acct = acct::find("id = ".$video['acct_id'])->getOne();
    //    $ws = (isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!='off')?'wss://':'ws://';
        $video['ws_url'] = "wss://".$_SERVER['SERVER_NAME'].'/wss';
        return $video;
        //密码观看
        
    }

    //判断用户是否有权限观看视频 true有权限 false无权限
    static function checkVideoAuth($video_id,$user_id,$password = null){
        $video = video::find("id = ".$video_id)->getOne();
        //无需密码和付费
        if($video->is_pay == 0 && $video->is_password == 0){
            return true;
        }
        //需要密码
        if($password && $video->is_password == 1 && $password == $video->password){
            return true;
        }
        //需要付费
        //直接购买
        if($video->is_pay == 1 && $video->is_pintuan == 0){
            $video_order = videoorder::find(array(
                    "video_id" => $video_id,
                    "user_id" => $user_id,
                    "status" => 1,
                    "is_pay" => 1,
                    "pintuan_id" =>0
                ))
            ->asArray()->getAll();
            if(count($video_order)>0){
                return true;
            }
        }
        //拼团
        if($video->is_pay == 1 && $video->is_pintuan == 1){
            $video_order = videoorder::find(array(
                    "video_id" => $video_id,
                    "user_id" => $user_id,
                    "status" => 1,
                    "is_pay" => 1
                ))
            ->getAll();
            foreach ($video_order as $v) {
                if($v->pintuan_detailid>0){
                    $pintuan = videopintuandetail::find("id = ".$v->pintuan_detailid)->getOne();
                    if($pintuan->need_num == $pintuan->join_num){
                        return true;
                    }
                }else{
                    return true;
                }
            }
            
        }
        //分享免费观看

        if($video->sharefree_open == 1){
            $share_log = videosharelog::find("user_id = ".$user_id." and video_id = ".$video_id)->getOne();
            if($share_log->sharefree_endtime >0 && $share_log->sharefree_endtime > time()){
                return true;
            }
        }
        //会员免费
        
        //获取用户vip等级
        $user_info = acctuser::find("id = ".$user_id)->getOne();
        if($user_info->viplevel_id>0 && $user_info->due_time > time()){

            //指定视频
            $varr = explode(",", $video->free_viplevelids);
            if(in_array($user_info->viplevel_id,$varr)){
                return true;
            }

            //指定分类
            //二级分类
            $s_category = educategory::find("id = ".$video->class_id)->getOne();

            //一级分类
            $f_category = educategory::find("id = ".$video->cat_id)->getOne();
            $sarr = explode(",",$s_category->free_viplevelids);
            $farr = explode(",",$f_category->free_viplevelids);
            array_merge($sarr,$farr);
            if(in_array($user_info->viplevel_id,$sarr)){
                return true;
            }

        }
        return false;

    }
    //首页直播
    static function indexlivelist($acct_id,$user_id,$limit=null){
        $time = time();
        $sql = "SELECT
            t.name as teacher_name,
            t.icon as teacher_icon,
            v.id,
            title,
            pic_url,
            is_order,
            page_view,
            video_time,
            style,
            is_password,
            opening_time,
            end_time
        FROM
            edu_video as v
            LEFT JOIN edu_video_teacher as t ON ( v.teacher_id = t.id )
        WHERE
            v.acct_id = $acct_id 
            AND v.status = 1 
            AND v.style = 3 
            AND v.index_show = 1 
        GROUP BY
            v.id 
        ORDER BY
            opening_time asc";
        if($limit){
            $sql = $sql." limit 0,$limit";
        }
        $live_index = QDB::getConn()->execute($sql)->fetchAll();

        if(count($live_index)){
            foreach ($live_index as &$v){
                $sum = QDB::getConn()->execute("select count(*) from edu_video_order where video_id = {$v['id']} and is_pay=1")->fetchAll();
                $v['order_sum'] = $sum[0]['count(*)'];
                if($v['opening_time']>=$time){
                    $v['live_status']=0;
                }elseif($v['opening_time']<$time ){
                    $v['live_status']=1;
                }
                $v['opening_time'] = date("H:i",$v['opening_time']);
            }
        }

        
        return $live_index;
    }

    //直播列表
    static function livelist($acct_id,$user_id){
        $time = time();
        $sql = "SELECT
            COUNT( o.id ) AS order_sum,
            t.name as teacher_name,
            t.icon as teacher_icon,
            v.id,
            title,
            pic_url,
            is_order,
            page_view,
            video_time,
            style,
            is_password,
            opening_time,
            present_price,
            original_price,
            shop_price
        FROM
            edu_video as v
            LEFT JOIN edu_video_order as o ON ( v.id = o.video_id AND o.is_pay = 1 )
            LEFT JOIN edu_video_teacher as t ON ( v.teacher_id = t.id )
        WHERE
            v.acct_id = $acct_id 
            AND v.status = 1 
            AND v.style = 3
        GROUP BY
            v.id 
        ORDER BY
            opening_time asc";
        $live = QDB::getConn()->execute($sql)->fetchAll();
        $in_live = array();
        $end_live = array();
        if(count($live)){
            for ($i=0; $i < count($live); $i++) { 
                $end_time = intval($live[$i]['opening_time'])+intval($live[$i]['video_time'])*60;
                if($end_time>$time){
                   array_push($in_live, $live[$i]); 
                }else{
                    array_push($end_live, $live[$i]); 
                }
            }

        }
        $res['inlive']=video::formatlivelist($in_live,$user_id);
        $res['endlive']=video::formatlivelist($end_live,$user_id);
        return $res;
    }

    //按日期格式化直播列表
    static function formatlivelist($live,$user_id){
        $res = array();
        $tmpdate = '';
        $d = -1;
        $c = 0;
        foreach ($live as $v){
            //user预约状态
            $date = date("Y-m-d",$v['opening_time']);
            $v['order_status'] = videoorder::checkorder($user_id,$v['id'])?1:0;
            $v['end_time'] = date("Y-m-d H:i",$v['opening_time']+$v['video_time']);
            $v['opening_time'] = date("Y-m-d H:i",$v['opening_time']);
            if($tmpdate != $date){
                $c=0;
                $d++;
                $tmpdate = $date;
                $res[$d]['name'] = $date;
                $res[$d]['info'] = array();
                $res[$d]['info'][$c]=$v;
                
                
            }else{
                $c++;
                $res[$d]['info'][$c]=$v;
            }
        }
        return $res;
    }

    //分类下视频列表
    static function classvideolist($acct_id,$class_id=0,$version=null){
        $live_auth = acct::checkversion($acct_id,$version);
        $condition = '';
        if(!$live_auth){
            $condition = " AND edu_video.style != 3 ";
        }
        $sql = "SELECT
            edu_video.id AS id,
            edu_video_tag.id AS tag_id,
            edu_video_tag.NAME AS tagname,
            position,
            color,
            title,
            pic_url,
            video_time,
            virtual_sellnum,
            virtual_pintuannum,
            is_order,
            introduce,
            money,
            page_view,
            style,
            edu_video.is_pay,
            is_password,
            opening_time,
            present_price,
            original_price,
            shop_price 
        FROM
            edu_video
            LEFT JOIN edu_video_tag ON ( edu_video.tag_id = edu_video_tag.id )
        WHERE
            edu_video.acct_id = $acct_id ";
        if ($class_id!=0) {
            $sql.=" AND class_id = $class_id ";
        }
        $sql.= $condition;
        $sql.=" AND edu_video.status = 1 ";
        $sql.=" ORDER BY  sort asc";
        $list = QDB::getConn()->execute($sql)->fetchAll();
        for ($i=0; $i < count($list); $i++) { 
            $list[$i]['virtual_sellnum']=intval($list[$i]['virtual_sellnum']);
            $list[$i]['virtual_pintuannum']=intval($list[$i]['virtual_pintuannum']);
        }
        return $list;
    }

    //直播开始通知
    static function startlivemsg($acct_id,$video_id){
        $template_id = video::getTemplateIdForTitle($acct_id,'课程即将开始提醒');
        if($template_id){
            $conf = acct::find("id = ".$acct_id)->getOne();
            $access_token = Helper_common::wx_get_token($conf->app_id,$conf->app_secret);
            if (!$access_token) {
                return [
                    'code' => 1,
                    'msg' => $access_token->errMsg,
                ];
            }
            $url="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$access_token";
            //获取预约用户
            $order = videoorder::find(array("video_id"=>$video_id,"is_pay"=>1))->getAll();
            $video = video::getvideoinfo($video_id);
            foreach ($order as $value) {
                if($value->form_id){
                    $user_info=acctuser::getuserinfo($value->user_id);
                    $data=array(
                        "touser"=>$user_info['wechat_open_id'],
                        "template_id"=>$template_id,
                        "page"=>"pages/live-class/live-class?video_id=$video_id",
                        "form_id"=>$value->form_id,
                        "data"=>array(
                                "keyword1"=>array("value"=>$video['title']),
                                "keyword2"=>array("value"=>date("Y-m-d",$video['opening_time'])),
                                "keyword3"=>array("value"=>date("H:i",$video['opening_time'])."~".date("H:i",$video['end_time']))
                                    )
                    );
                    $res = Helper_common::post_data($url,$data);
                    $value->form_id="";
                    $value->save();
                }
            }

        }

    }

    static function getTemplateIdForTitle($acct_id,$title){
        $list = video::getTemplateList($acct_id);
        for ($i=0; $i < count($list); $i++) { 
            if($list[$i]['title']==$title){
                return $list[$i]['template_id'];
            }
        }
        return false;
    }

    static function getTemplateList($acct_id){

        $conf = acct::find("id = ".$acct_id)->getOne();
        $access_token = Helper_common::wx_get_token($conf->app_id,$conf->app_secret);
        
        if (!$access_token) {
            return [
                'code' => 1,
                'msg' => $access_token->errMsg,
            ];
        }

        $url="https://api.weixin.qq.com/cgi-bin/wxopen/template/list?access_token=$access_token";
         $data = json_encode([
            'offset' => 0,
            'count' => 20
        ]);

        $response = Helper_common::send_post($url, $data);
        $response = json_decode($response,true);
        if($response['errcode']==0){
            return $response['list'];
        }else{
            return [];
        }

    }
    /**
     * 首页视频课程
     * @Author   xy
     * @DateTime 2019-10-14T12:17:32+0800
     * @param    [type]                   $acct_id [description]
     * @return   [type]                            [description]
     */
    static function getindexvideo($acct_id){
        $res = self::find(array("acct_id"=>$acct_id,"status"=>1,"index_show"=>1))->order("sort asc,id desc")->asArray()->getAll();
        return $res;
    }

    static function getLiveRoomUserNumber($video_id,$host,$redis){
        $pool = $redis->get("edulive:$host:socket_pool:live:".$video_id);
        $user_arr = [];
        // $count = 0;
        if($pool){
            $pool_arr = json_decode($pool,true);
            foreach ($pool_arr as $key => $value) {
                $rd = $redis->get("edulive:$host:socket_pool:connects:".$value);
                if($rd){
                    $rd_arr = json_decode($rd,true);
                    if(!empty($rd_arr['openid'])){
                        array_push($user_arr,$rd_arr['openid']);
                    }
                }
            }
        }

        if(!empty($user_arr)){
            array_unique($user_arr);
        }
        return count($user_arr);
    }
}

